#include "book.h"

//节点创建
ListNode* BuyDListNode(TYPE x) {
	ListNode* new_node = (ListNode*)malloc(sizeof(ListNode));
	if (!new_node) {
		perror("new_node");
		return NULL;
	}
	new_node->next = NULL;
	new_node->prev = NULL;
	new_node->val = x;
	return new_node;
}

//头节点的创建
ListNode* ListCreate() {
	ListNode* head = BuyDListNode(0);//此处所赋0无任何意义
	head->next = head;
	head->prev = head;
	return head;
}

//销毁
void ListDestory(ListNode** plist) {
	assert(plist);
	ListNode* cur = (*plist)->next;
	ListNode* next = NULL;
	//销毁有效节点
	while (cur != *plist) {
		next = cur->next;
		free(cur);
		cur = next;
	}
	//销毁头节点
	free(*plist);
	*plist = NULL;
}

//头插
void ListPushHead(ListNode* plist, TYPE x) {
	assert(plist);
	ListNode* new_node = BuyDListNode(x);
	new_node->next = plist->next;
	new_node->prev = plist;
	plist->next->prev = new_node;
	plist->next = new_node;
	return;
}


//尾插(每插入一个节点，需要修改4个指针域)
void ListPushBack(ListNode* plist, TYPE x) {
	assert(plist);
	ListNode* new_node = BuyDListNode(x);
	new_node->prev = plist->prev;
	new_node->next= plist;
	//new_node->prev->next = new_node;
	plist->prev->next = new_node;
	plist->prev = new_node;
	return;
}

//头删
extern void ListPopHead(ListNode* plist) {
	if (ListEmpty(plist))
		return;
	ListNode* del_node = plist->next;
	plist->next = del_node->next;
	del_node->next->prev = plist;
	free(del_node);
	return;
}

//尾删(1和多不区分)
void ListPopBack(ListNode* plist) {
	//assert(plist);--检验空中已进行该操作
	if (ListEmpty(plist))
		return;
	ListNode* del_node = plist->prev;
	del_node->prev->next = plist;
	plist->prev = del_node->prev;
	free(del_node);
	return;
}

//任意位置插入
void ListPushFront(ListNode* pos, TYPE x) {
	assert(pos);
	ListNode* new_node = BuyDListNode(x);
	new_node->next = pos;
	new_node->prev = pos->prev;
	pos->prev->next = new_node;
	pos->prev = new_node;
	return;
}

//任意位置删除
extern void ListPop(ListNode* pos) {
	assert(pos);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	return;
}

//检验是否为空（只有头）
int ListEmpty(ListNode* plist)
{
	assert(plist);
	return plist->next == plist;
}

//查找
extern ListNode* ListFind(ListNode* plist, TYPE x) {
	assert(plist);
	ListNode* cur = plist->next;
	while (cur != plist) {
		if (cur->val == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}
//打印
void PrintNode(ListNode* plist)
{
	assert(plist);
	ListNode* cur = plist->next;
	while (cur != plist) {
		printf("%d  ", cur->val);
		cur = cur->next;
	}
	printf("\n");
}


void TestNode()
{
	ListNode* plist = ListCreate();
	ListPushBack(plist, 4);
	ListPushHead(plist, 5);
	ListPushBack(plist, 3);
	ListPushHead(plist, 6);
	ListPushBack(plist, 2);
	ListPushBack(plist, 1);
	PrintNode(plist);

	ListPopBack(plist);
	PrintNode(plist);
	
	ListPopBack(plist);
	PrintNode(plist);
	
	ListPushFront(ListFind(plist, 4), 10);

	ListPopHead(plist);
	PrintNode(plist);

	ListPop(ListFind(plist, 4));
	PrintNode(plist);
	ListDestory(&plist);
	
	return;
	return;
}